<template>
	<view>
		<view style="padding:20rpx">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form1" labelWidth="100">
				<u-form-item label="商品类别" prop="dtypeName" borderBottom @click="showPopup">
					<u--input v-model="form.dtypeName" border="none" disabled placeholder="请选择类别"></u--input>
				</u-form-item>
				<u-form-item label="商品名称" prop="dname" borderBottom >
					<u--input v-model="form.dname" border="none" placeholder="请输入名称"></u--input>
				</u-form-item>
				<u-form-item label="菜品编号" prop="disheCode" borderBottom >
					<u--input v-model="form.disheCode" type="number" border="none" placeholder="请输入菜品编号"></u--input>
				</u-form-item>
				<u-form-item label="商品图片" prop="dname" borderBottom >
					<u-upload :fileList="fileList" @afterRead="afterRead" imageMode="scaleToFill" name="1" :maxCount="1"
						previewImage class="uimg">
						<view v-if="form.dimg">
							<image :src="userlogo" class="dplogo"/>
						</view>
					</u-upload>
				</u-form-item>
				<u-form-item label="是否刷卡取餐" prop="state" borderBottom >
					<radio-group
					  @change="onChangeState" 
					>   
						<label v-for="(item, index) in radiolist" :key="item.value" style="padding-right:20rpx">
							<radio :value="item.value" :checked="index === current" color="#F66B71"/>
							<text>{{item.name}}</text>
						</label>
					</radio-group>
				</u-form-item>
				<u-form-item label="价格" prop="dprice" borderBottom >
					<u--input v-model="form.dprice" border="none" placeholder="请输入价格"></u--input>
				</u-form-item>
				<div class="oboard" v-for = "(item,index) in specData">
				  <u--form ref="addForm" :model="item" :rules="item.rules" label-width="110px">
					<u-form-item label="菜品规格名称" prop="speType" style="margin-left:10px">
					  <input v-model="item.speType" placeholder="请输入规格名称" style="width:100%;font-size:14px"/> 
					</u-form-item>
					<view style="display:flex;padding:10upx 0px">
						<u-button type="success" size="small" @click="addRowDet(index)" style="width:200upx;margin-left:10px">添加规格明细</u-button>
						<u-button type="error" :plain="true" size="small" @click="removeRowDet(index,item)" style="width:200upx;margin-left:10px">删除规格</u-button>
					</view>
					
					<div v-for="(it,idx) in item.detail" style="margin:10px;padding:0px 5px 5px 5px;border:1px dotted #ccc">
						<div style="display: flex;">
						  <div>
							  <u-form-item label="规格明细名称" prop="speTypeItem">
								<input v-model="it.speTypeItem" placeholder="请输入规格明细名称" style="font-size:14px"/>
							  </u-form-item>
							  <u-form-item label="规格明细价格" prop="spePrice">
								<input v-model="it.spePrice" placeholder="请输入规格价格" style="font-size:14px"/>
							  </u-form-item>
						  </div>
						  <u-icon name="trash-fill" @click="removeRow(it,index,idx)" size="20" color="#F66B71"></u-icon>
					  </div>
					   <u-button type="success" @click="ddsTest(it,item)" v-if="isEdit">确定</u-button>
					<!--  <u-button type="error" size="small" >删除规格明细</u-button> -->
					  <!-- <u-form-item label="使用标识" prop="isflag">
						<el-radio-group v-model="it.isflag">
						  <el-radio
							v-for="dict in isflagOpts"
							:key="dict.value"
							:label="dict.value"
						  >{{dict.label}}</el-radio>
						</el-radio-group>
					  </u-form-item> -->
					</div>
				  </u--form>
				</div>
				<view style="width:200upx;margin-top:20upx;margin-left:20upx">
					<u-button type="success" :plain="true" size="small" @click="addRow()" >添加规格</u-button>
				</view>
			</u--form>
			<u-button class="editbtn" type="primary" size="large" round @click="submitForm">提交</u-button>
		</view>
		
		<u-picker :show="showGosCate" :columns="cateList" title="商品分类" @confirm="onConFrim"
			@cancel="onClose"></u-picker>
	</view>
</template>

<script>
	import Config from '@/util/index.js'
	import {getGoodsType,queryGoodsOne,addDishes} from '@/api/goods'
	export default {
		data() {
			return {
				fileList: [],
				showGosCate: false,
				gstate: '0',
				radio: '0',
				astate: '0',
				userlogo: "",
				current: 0,
				radiolist:[
					{
						value: '0',
						name: '否'
					},
					{
						value: '1',
						name: '是',
						checked: 'true'
					}
				],
				isEdit:false,
				specData:[
					{
					    dishesId:'',
					    speType:'',
					    detail:[
							{
							  speTypeItem:'',
							  spePrice:'',
							  isflag:1
							}
						]
					}        
			    ],
				goddscate: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
				userInfo: {},
				option1: [], //分类
				goodsInfo:{},
				goodstypename: '',
				mid: '',
				vcode: '',
				dname: '', //  商品名称
				dpic: '', //商品图片存放地址
				dishdesc: '',
				dprice: "", // 价格   数字  精度为小数点后一位
				dcode: '',
				imgpath: '',
				cateList:[],
				form: {
					aiCode:null,
					shopId:null,
					dishesId: null,
					deptId:null,
					dtype: null,
					dname: null,
					dimg: "",
					disheCode:'',
					dishesId:'',
					pickupFlag:1,
					dprice: null,
					qrcode: null,
					restShopDisheSpecs:[],
					examineFlag: 1,
					salesFlag: 1,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null
				},
				rules:{
					'dname': {
						type: 'string',
						required: true,
						message: '请填写商品名称',
						trigger: ['blur', 'change']
					},
					'dprice': {
						type: 'number',
						required: true,
						message: '请填写商品价格',
						trigger: ['blur', 'change']
					}
				}
			}
		},
		onLoad(options) {
			this.form.dishesId = options.goid
			this.form.shopId = options.shopid
			this.form.deptId = options.rcode
			this.mid = uni.getStorageSync('loginInfo').mid
			this.imgpath = Config.get('apiUrl')
			this.queryGoodsType()
			if(this.form.dishesId){
				this.reset();
				let params = {
					dishesId:options.goid				
				}
			  queryGoodsOne(params).catch(response => {
				if(response.data.code==200){
					if(response.data.dishe.restShopDisheSpecs.length>0){
					  let tdata = this.groupBy(response.data.dishe.restShopDisheSpecs, 'speType');
					  let names = Object.keys(tdata)
					  this.specData=[]
					  for(let i=0;i<names.length;i++){
						let xx = {
						  dishesId:response.data.dishesId,
						  speType:names[i],
						  detail:tdata[names[i]]
						}        
						this.specData.push(xx)
					  }
					}else{
					  this.specData = [
						{
						  dishesId:response.data.dishesId,
						  speType:'',
						  detail:[
							{
							  speTypeItem:'',
							  spePrice:'',
							  isflag:1
							}
						  ]
						}        
					  ]
					}
				}
				this.form = response.data.dishe;
				let dpt = this.option1.filter(item =>{
					return item.value = response.data.dishe.dtype
				})[0]
				this.form.dtypeName = dpt.text
				this.form.dimg = response.data.dishe.dimg
				this.form.dprice = parseInt(response.data.dishe.dprice)
				this.userlogo = this.imgpath + response.data.dishe.dimg
				this.form.pickupFlag = parseInt(response.data.dishe.pickupFlag)
				this.isEdit = true
			  });
			}
		},
		methods: {
			onClose() {
				this.showGosCate = false
			},
			groupBy(array, key){
			  return array.reduce((result, currentItem) => {
				// 使用 key 的值作为分组的键
				const groupKey = currentItem[key];
				// 如果 result 中不存在这个键，则创建它
				if (!result[groupKey]) {
				  result[groupKey] = [];
				}
				// 将当前项添加到对应的分组中
				let obj = {
				  speId:currentItem.speId,
				  // speType:currentItem.speType,
				  speTypeItem:currentItem.speTypeItem,
				  spePrice:currentItem.spePrice,
				  isflag:parseInt(currentItem.isflag)
				}
				result[groupKey].push(obj);
				return result;
			  }, {});
			},
			showPopup() {
				this.showGosCate = true
			},
			reset() {
			  this.form = {
				aiCode:null,
				shopId:null,
				dishesId: null,
				deptId:null,
				dtype: null,
				dname: null,
				dimg: "",
				pickupFlag:1,
				dprice: null,
				qrcode: null,
				restShopDisheSpecs:[],
				examineFlag: 1,
				salesFlag: 1,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null
			  }
			},
			submitForm() {
			     /// 获取对象
			      // let target = e.target
			      // if (target.nodeName === 'SPAN' || target.nodeName === 'I') {
			      //   target = e.target.parentNode;
			      // }
			      // // 让其失去焦点
			      // target.blur();
			      this.form.restShopDisheSpecs=[]
			      let num = 0
			      try{
			        this.specData.forEach(item=>{
			          if(item){
			            item.detail.forEach(it=>{
			              if(!it.speTypeItem){
			                num++
							uni.showToast({
								title: "规格明细不能为空",
								icon: 'none',
								duration: 2000
							});
			                throw("规格明细不能为空")
			              }
			              if(it.spePrice){
			                let res = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
			                if(!res.test(it.spePrice)){
			                  num++
							  uni.showToast({
							  	title: "价格请输入正数,最多保留两位小数",
							  	icon: 'none',
							  	duration: 2000
							  });
			                  throw("价格请输入正数,最多保留两位小数")
			                }
			              }
			              let params = {}
			              params.speType = item.speType
			              params.speId = it.speId
			              params.speTypeItem = it.speTypeItem
			              params.spePrice = it.spePrice
			              params.isflag = it.isflag
			              this.form.restShopDisheSpecs.push(params)
			            })
			          }
			        })
			      }catch(e){
			        console.log("终止循环")
			      }
			        if(num==0){
			            if (this.form.dishesId != null) {
							updateDishesSpec(this.form).catch(response => {
								if(response.data.code==200){
									uni.showToast({
										title: "修改成功",
										icon: 'none',
										duration: 2000
									});
								}
							});
			            } else {
							addDishes(this.form).catch(response => {
								if(response.data.code==200){
									uni.showToast({
										title: "新增成功",
										icon: 'none',
										duration: 2000
									});
								}
							});
			            }
			        }
			    },
		   addRow(){
			  let params = {
				speType:'',
				dishesId: this.dishesId,
				detail:[]
			  }
			  this.specData.push(params)
			},
			removeRowDet(idx,item){
			  let ids = []
			  if(item.detail.length>0){
				if(this.form.restShopDisheSpecs.length>0){
				  this.form.restShopDisheSpecs.forEach(it=>{
					if(it.speId){
					  ids.push(it.speId)
					}
				  })
				  this.$modal.confirm('是否确认删除规格为"' + item.speType + '"的数据项？').then(function() {
					return delDishesSpecs(ids);
				  }).then(() => {
					this.specData.splice(idx,1)
				  })
				}else{
				  if(this.specData.length>1){
					this.specData.splice(idx,1)
				  }
				}
			  }else{
				this.specData.splice(idx,1)
			  }
			},
		   removeRow(item,pid,cid){
			  let params = item.speId;
			  if(params){
				this.$modal.confirm('是否确认删除规格明细为"' + item.speTypeItem + '"的数据项？').then(function() {
				  return delDishesSpecs(params);
				}).then(() => {
				  let idxs =  this.specData[pid].detail.length-1
				  if(pid==1){
					this.specData[pid].detail.splice(cid,1)
				  }else{
					if(idxs>0){
					  this.specData[pid].detail.splice(cid,1)
					}
				  }
				  this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			  }else{
				this.specData[pid].detail.splice(cid,1)
			  }
			},
			ddsTest(item,prow){
			  if(item.speTypeItem){
				let params = {
				  dishesId:prow.dishesId,
				  speId: item.speId,
				  isflag:1,
				  speType: prow.speType,
				  speTypeItem: item.speTypeItem,
				  spePrice: item.spePrice
				}
				if (item.speId) {
				  updateDishesSpecs(params).then(response => {
					this.$modal.msgSuccess("修改成功");
				  });
				} else {
				  addDishesSpecs(params).then(response => {
					this.$modal.msgSuccess("新增成功");
				  });
				}
			  }
			},
			addRowDet(idx){
			  let params = {
				// speType:"",
				speTypeItem:"",
				spePrice: "",
				isflag: 1,
				rules:{
					speType: [
					  { required: true, message: "规格名称不能为空", trigger: "blur" }
					],
					speTypeItem: [
					  { required: true, message: "规格名称明细不能为空", trigger: "blur" }
					]
				  }
			  }
			  this.specData[idx].detail.push(params)
			},
			onConFrim(event) {
				let index = event.indexs[0]
				this.form.dtypeName = event.value[0]
				let dpt = this.option1.filter(item =>{
					return item.text = this.form.dtypeName
				})[0]
				this.form.dtype = dpt.value
				console.log("dtype",this.form.dtype)
				this.showGosCate = false
			},
			onChangerad(event) {
				// this.radio = event.detail
				this.goodsInfo.shopisflag = event
			},
			onChangeState(evt) {
				// this.gstate = event.detail
				for (let i = 0; i < this.radiolist.length; i++) {
					if (this.radiolist[i].value === evt.target.value) {
						this.form.pickupFlag = i;
						break;
					}
				}
			},
			onChangeAState(event) {
				this.astate = event.detail
			},
			queryGoodsType() {
				/**
				 * 得到产品分类
				 */
				let _this = this;
				getGoodsType().catch(result => {
					let type = []
					let cateList = []
					result.data.rows.map(item => {
						let obj = {}
						obj.text = item.dtypeName
						obj.value = item.dtype
						cateList.push(item.dtypeName)
						type.push(obj)
					})
					_this.option1 = type
					// cateList.splice(0, 1),
					_this.cateList.push(cateList)
				})
			},

			saveGoods() {
				let astate = 0;
				if (this.goodsInfo.astate) {
					astate == this.goodsInfo.astate
				}
				let spdesc = this.goodsInfo.dishdesc
				if (spdesc == '"null"') {
					spdesc = ""
				}
				let params = {
					dishes: {
						dcode: this.dcode,
						management: {
							mid: this.mid
						},
						variety: {
							vcode: this.vcode
						},
						dname: this.goodsInfo.dname,
						dprice: this.goodsInfo.dprice,
						dishdesc: spdesc,
						dpic: this.goodsInfo.dpic,
						state: this.current,
						astate: astate,
						bookflag: this.goodsInfo.bookflag,
						booktime: ""
					}
				}
				if (this.dpic == "") {
					uni.showToast({
						title: "请先上传商品图片！",
						icon: 'none',
						duration: 2000
					});
					return false
				}
				if (this.goodstypename == "") {
					uni.showToast({
						title: "商品类别不能为空",
						icon: 'none',
						duration: 2000
					});
					return false
				}
				if (this.goodsInfo.dname == "") {
					uni.showToast({
						title: "商品名称不能为空",
						icon: 'none',
						duration: 2000
					});
					return false
				}
				if (this.goodsInfo.dprice == "") {
					uni.showToast({
						title: "商品价格不能为空",
						icon: 'none',
						duration: 2000
					});
					return false
				}
				// if(this.data.dishdesc == ""){
				//   uni.showToast({
				//     title:"商品介绍不能为空",
				//     icon: 'none',
				//     duration: 2000
				//   });
				//   return false
				// }
				let _this = this
				Api.addGoods(params).then(res => {
					if (res.retCode == 0) {
						if (_this.dcode) {
							uni.showToast({
								title: "修改成功",
								icon: 'none',
								duration: 2000
							});
						} else {
							uni.showToast({
								title: "添加成功",
								icon: 'none',
								duration: 2000
							});
						}
						var pages = getCurrentPages();
						var prevPage = pages[pages.length - 2]; //上一个页面
						uni.navigateTo({
							url:'index'
						})
					} else {
						uni.showToast({
							title: res.info,
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			beforeRead(event) {
				const {
					file,
					callback
				} = event.file;
				callback(file.type === 'image');
			},
			afterRead(event) {
				let file = event.file;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let _this = this
				uni.uploadFile({
					url: _this.imgpath + '/common/upload',
					filePath: file.url,
					name: 'file',
					success(res) {
						console.log("xxssdd",res)
						// 上传完成需要更新 fileList
						const {
							fileList = []
						} = res.data;
						fileList.push({
							...file,
							url: res.data
						});
						_this.fileList = fileList;
						let logoImg = JSON.parse(res.data).relationPath
						
						_this.userlogo = _this.imgpath + logoImg
						_this.form.dimg = logoImg
					}
			    });
	        },
			updataState() {
				let params = {
					dcode: '',
					state: '' //0销售，1停售
				}
				let _this = this
				Api.goodsStateUpdata(params).then(res => {
					console.log("info", res)
					_this.storeInfo = res.management
				})
			}
	    }
	}
</script>

<style scoped>
	.oboard .uni-button{
		margin-left: 0 !important;
	}
	.oboard{
		  width: 96%;
		  height: auto;
		  background-color: #f0f0f0;
		  margin:10px auto;
		  padding-bottom:10upx;
		  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);
	}
	.dplogo {
		width: 150rpx;
		height: 150rpx;
		margin: 20rpx auto;
	}

	.editbtn {
		width: 96%;
		height: 60rpx;
		margin:20upx auto
	}
	.uimg{width:150rpx;height:150rpx;margin:0rpx auto}
	.custom-class {
		height: 50rpx !important
	}

	.van-picker__toolbar {
		position: absolute;
		width: 100%;
		z-index: 999;
	}

	.spyd {
		display: flex;
		text-align: center;
		height: 90rpx;
		line-height: 90rpx;
		border-bottom: 1px solid #EEEEF4;
		font-size: 0.8rem;
	}
</style>
